// components/custom-form-item/index.js
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import { formatTime, getDatetime, debounce, initLocationPersmiss } from "../../utils/util"
import { isDockingEvent } from "../../utils/hooks"
import subPub from "../../utils/subPub"
const $api = require("../../request/api").API
const app = getApp()
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    formItem: {
      type: Object,
    },
    currentIndex: {
      type: Number
    },
    edit: {
      type: Boolean,
      value: false,
    },
  },
  options: {
    styleIsolation: 'shared'
  },
  /**
  * 组件的初始数据
  */
  data: {
    showSelectList: false,
    showInputSelect: false,
    // 选择项
    selectList: [],
    // 下拉选择的id与name
    selectedNames: "",
    selectedIds: "",
    // 输入的值
    inputValue: "",
    showDate: false,
    dateType: "datetime", //默认值为datetime，可选为date、time、year-month
    // 开始日期
    beginDate: "",
    // 开始格式化的日期
    beginDateFormat: "",
    // 结束日期
    endDate: "",
    // 结束格式化日期
    endDateFormat: "",
    // 是开始还是结束日期
    beginEnd: true,//true为开始时间
    // 当前的时间
    currentDate: Date.now(),
    // 最小时间十年前
    minDate: new Date(String(new Date().getFullYear() - 10)).getTime(),
    // 最大时间十年后
    maxDate: new Date(String(new Date().getFullYear() + 10)).getTime(),
    // 时间
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      if (type === 'day') {
        return `${value}日`
      }
      if (type === 'hour') {
        return `${value}时`
      }
      if (type === 'minute') {
        return `${value}分`
      }
      return value;
    },
    filter(type, options) {
      if (type === 'minute') {
        return options.filter((option) => option % 15 === 0);
      }
      return options;
    },
    values: [],
    // 照片
    imgList: [],
    // 视频
    video: '',
    // 录音
    recordSound:"",
    // 单选
    radio: "",
    radioList: [],
    fieldName: "",
    // 定位地址
    address:"",
    // 定位经纬度
    latitude:"",
    longitude:"",
  },
  observers: {
    formItem(formItem) {
      let { value, fieldType, fieldOptions, fieldName, dockData,attrName } = formItem
      const base64Reg = /^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$/
      let values = formItem.values || [] // 历史记录
      let eventId = app.globalData['btnList.eventId']
      this.setData({
        fieldName: fieldName || "",
        dockData,
        attrName,
        eventId
      })
      switch (fieldType) {
        case 1:
          this.setData({
            inputValue: value || "",
            // fieldName: fieldName || "",
            values
          })
          if (fieldName == 'consumer') {
            this.getSelectList()
          }
          break;
        case 2:
          this.setData({
            selectedIds: value || "",
            selectList: fieldOptions ? JSON.parse(fieldOptions) : []
          })
          if (value) {
            let selectedIds = value.split(",")
            let selectedNames = ""
            if (eventId==18&&fieldName=='timerinterval'&&dockData) {
              // 如果字段是挂号的话就就把value的值作为name显示
              selectedNames = value
            } else {
              selectedIds.forEach(item => {
                this.data.selectList.find(item2 => {
                  if (item == item2.id) {
                    item2.selected = true
                    selectedNames = selectedNames ? selectedNames + ',' + item2.name : item2.name
                  }
                })

              })
            }
            this.setData({
              selectedIds: selectedIds,
              selectedNames: selectedNames,
              selectList: this.data.selectList,
            })
          }
          break;
        case 3:
          let arr = value?value.split(","):[]
          this.setData({
            beginDateFormat: arr[0] ? arr[0] : '',
            endDateFormat: arr[1] ? arr[1] : '',
            beginDate: arr[0] ? getDatetime(arr[0]).getTime() : '',
            endDate: arr[1] ? getDatetime(arr[1]).getTime() : '',
            // dateType:dockData?'date':'datetime',
            // minDate:new Date(String(new Date().getFullYear() - 100)).getTime() // 一百年前可选
          })

          if(eventId==19&&dockData&&fieldName=='date'){
            // 影像预约的日期
            this.setData({
              minDate:new Date().getTime(),
              dateType:'date'
            })
          }
          if(dockData&&fieldName=='birthdate'){
            // 出生日期
            this.setData({
              dateType:'date',
              minDate:new Date(String(new Date().getFullYear() - 100)).getTime() // 一百年前可选
            })
          }
        case 4:
            value = (value?value.split(","):[])
            // 如果存在base64就不赋值
            if(value.some(item=>base64Reg.test(item))) return
            this.setData({
              imgList:value
            })
          break
        case 5:
          // 如果存在base64那么就不赋值
          if(base64Reg.test(value)) return
          this.setData({
            video: value || ""
          })
          break
        case 6:
          this.setData({
            radio: value || "",
            radioList: fieldOptions ? JSON.parse(fieldOptions) : []
          })
          break
        case 7:
          const {address="",latitude="",longitude=""} = value?JSON.parse(value):{}
          if(address){
            this.setData({
              address,
              latitude,
              longitude,
            })
          }else if(!this.data.longitude){
            // 如果经纬度也不存在就重新定位
            this.getLocation()
          }
          break
        case 8:
          // 如果存在base64那么就不赋值
          if(base64Reg.test(value)) return
          this.setData({
            recordSound: value || ""
          })
          break
      }
    }
  },
  lifetimes: {
    // ready() {
    //   let formItem = this.data.formItem
    //   let value = formItem.value
    //   let fieldType = formItem.fieldType
    //   let fieldOptions = formItem.fieldOptions
    //   let fieldName = formItem.fieldName
    //   let values = formItem.values||[]
    //   switch (fieldType) {
    //     case 1:
    //       this.setData({
    //         inputValue: value || "",
    //         fieldName: fieldName || "",
    //         values
    //       })
    //       if(fieldName=='consumer'){
    //         this.getSelectList()
    //       }
    //       break;
    //     case 2:
    //       this.setData({
    //         selectedIds: value || "",
    //         selectList: fieldOptions ? JSON.parse(fieldOptions) : []
    //       })
    //       if (value) {
    //         let selectedIds = value.split(",")
    //         let selectedNames = ""
    //         selectedIds.forEach(item => {
    //           this.data.selectList.find(item2 => {
    //             if (item == item2.id) {
    //               item2.selected = true
    //               selectedNames = selectedNames ? selectedNames + ',' + item2.name : item2.name
    //             }
    //           })

    //         })
    //         this.setData({
    //           selectedIds: selectedIds,
    //           selectedNames: selectedNames,
    //           selectList: this.data.selectList
    //         })
    //       }
    //       break;
    //     case 3:
    //       if (value) {
    //         let arr = value.split(",")
    //         this.setData({
    //           beginDateFormat: arr[0] ? arr[0] : '',
    //           endDateFormat: arr[1] ? arr[1] : '',
    //           beginDate: arr[0] ? getDatetime(arr[0]).getTime() : '',
    //           endDate: arr[1] ? getDatetime(arr[1]).getTime() : ''
    //         })
    //       }
    //     case 4:
    //       this.setData({
    //         imgList: value ? value.split(",") : []
    //       })
    //       break
    //     case 5:
    //       this.setData({
    //         video: value || ""
    //       })
    //       break
    //     case 6:
    //       this.setData({
    //         radio: value || "",
    //         radioList: fieldOptions ? JSON.parse(fieldOptions) : []
    //       })
    //   }
    // }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    // 扫码
    scanCode() {
      wx.scanCode({
        scanType: ['barCode', 'qrCode'],
        success: res => {
          this.setData({
            inputValue: res.result
          })
          this.modifyData()
        },
        fail: err => {
          Toast.fail("扫码失败")
        }
      })
    },
    showInputSelectPopup() {
      this.setData({
        showInputSelect: true
      })

    },
    // 输入选择和扫码一样
    inputSelect(e) {
      const { value } = e.detail;
      this.setData({
        inputValue: value,
        showInputSelect: false,
      })
      this.modifyData()
    },
    // 搜索
    async search() {
        const { inputValue, attrName, dockData,fieldName,eventId } = this.data
        if (!inputValue) return Toast.fail(`请输入${attrName}`)
        if(!dockData) return
        if (fieldName == 'patientCard') {
          const params = {idCard:inputValue,variantId:app.globalData['btnList.variantId']}
          let data = await $api.getThirdPersonInfoByIdCard(params)
          data = data.data.data
          if(!data) return Toast.fail(`暂无搜索到数据`)
          this.triggerEvent("getSearchData", { data })
        }
      // }
      // switch (String(dockData)) {
      //   case '1':
      //     const params = {idCard:inputValue}
      //     if(eventId==18){
      //       // 挂号
      //     }else if(eventId==19){
      //       // 影像预约
      //       params.doctorId = app.globalData["dock.doctorId"]
      //     }

      //     // 对接挂号
      //     if (fieldName == 'patientCard') {
      //       let data = await $api.getThirdPersonInfoByIdCard(params)
      //       data = data.data.data
      //       if(!data) return Toast.fail(`暂无搜索到数据`)
      //       this.triggerEvent("getSearchData", { data })
      //     }
    
         
      //     break
      // }

    },
    closeInputSelectPopup() {
      this.setData({
        showInputSelect: false
      })
    },
    // 获取输入框选择的数据
    getSelectList() {
      const selectList = app.globalData['custom-form-selectedList'] || []
      if (selectList.length) {
        this.setData({
          selectList,
        })
        delete app.globalData['custom-form-selectedList']
      } else {
        // 这里添加一个监听，如果有数据的话就获取
        const id = subPub.on("getBeeperCustomerList", selectList => {
          this.setData({
            selectList
          })
          subPub.off("getBeeperCustomerList", id)
        })
      }
    },
    // 输入
    inputChange: debounce(function (e) {
      this.setData({
        inputValue: e.detail.value
      })
      this.modifyData()
    }, 200),
    // 显示下拉选择
    async showSelectPopup() {
      const { fieldName, dockData,eventId } = this.data
      if (fieldName == 'timerinterval'&&eventId==18&&dockData) {
        // 如果是挂号的话就需要调接口请求数据
        let res = await $api.getListDoctorTime({ date: app.globalData['dock.date'], doctorId: app.globalData['dock.doctorId'] })
        res = res.data.data || []
        this.setData({
          selectList: res.map(item => {
            const value = `${item.begintime}-${item.endtime}`
            return {
              id: value,
              name: value
            }
          })
        })
      }
      this.setData({
        showSelectList: true
      })
    },
    // 关闭下拉选择
    closeSelectPopup() {
      this.setData({
        showSelectList: false,
      })
    },
    // 选择
    selectTarget(e) {
      let index = e.currentTarget.dataset.index
      const {selectList,dockData,fieldName} = this.data
      const eventId = app.globalData['btnList.eventId']
      // let selectList = selectList
      if (index || index === 0) {
        if (!this.data.formItem.multiFlag) {
          // 不是多选
          selectList.forEach((item, index2) => {
            if (index2 != index) delete item.selected
          })
        }
        if (selectList[index].hasOwnProperty('selected')) {
          selectList[index].selected = !selectList[index].selected
        } else {
          selectList[index].selected = true
        }
        const targetArr = selectList.filter(item => item.selected)
        let selectedIds = targetArr.map(item => item.id)
        let selectedNames = targetArr.map(item => item.name)
        if (eventId == 18&&fieldName=='timerinterval'&&dockData) {
          app.globalData['dock.timerinterval'] = selectedIds[0]
          this.closeSelectPopup()
        }
        this.setData({
          selectedIds: selectedIds.length > 0 ? selectedIds.join(",") : '',
          selectedNames: selectedNames.length > 0 ? selectedNames.join(",") : '',
          selectList: selectList,
        })
        this.modifyData()
        // if(eventId==18&&fieldName=='timerinterval'){
        //   this.closeSelectPopup()
        // }
      }
    },
    // 清除全部选择
    clearAllSelect() {
      this.data.selectList.forEach(item => {
        if (item.selected) delete item.selected
      })
      this.setData({
        selectedNames: "",
        selectedIds: "",
        selectList: this.data.selectList,
      })
      this.modifyData()
    },
    // 打开时间选择弹框
    showDatePopup(e) {
      let flag = e.currentTarget.dataset.flag
      this.setData({
        beginEnd: flag ? true : false,
        showDate: true,
      })

      if (this.data.beginEnd && this.data.beginDate) {
        this.setData({
          currentDate: this.data.beginDate
        })
      } else if (!this.data.beginEnd && this.data.endDate) {
        this.setData({
          currentDate: this.data.endDate
        })
      } else {
        this.setData(
          this.setData({
            currentDate: Date.now()
          })
        )
      }
    },
    //关闭时间弹框
    closeDatePopup() {
      this.setData({
        showDate: false
      })
    },
    // 时间
    dateChange(e) {
      let value = formatTime(e.detail, this.data.dateType)
      if (this.data.beginEnd) {
        if (this.data.endDate && e.detail > this.data.endDate) {
          Toast.fail("开始时间不能大于结束时间")
          return
        }
        this.setData({
          beginDate: e.detail,
          beginDateFormat: value
        })
      } else {
        if (this.data.beginDate && this.data.beginDate > e.detail) {
          Toast.fail("结束时间不能小于开始时间")
          return
        }
        this.setData({
          endDate: e.detail,
          endDateFormat: value
        })
      }
      this.setData({
        showDate: false,
        currentDatetime: e.detail
      })
      this.modifyData()
    },
    // 删除
    delete(e) {
      let prop = e.currentTarget.dataset.prop
      const modifyData = {}
      switch(prop){
        case "inputValue":
          modifyData.inputValue = ''
          break
        case "beginDate":
          modifyData.beginDate = ""
          modifyData.beginDateFormat = ""
          break
        case "endDate":
          modifyData.endDate = ""
          modifyData.endDateFormat = ""
          break
        case "address":
          // 这里经纬度不清除做一个标记
          modifyData.address = ""
          // modifyData.latitude = ""
          // modifyData.longitude = ""
          break
      }
      this.setData(modifyData)
      this.modifyData()
      // if (prop == "inputValue") {
      //   this.setData({
      //     inputValue: ""
      //   })
      //   this.modifyData()
      // }
      // if (prop == 'beginDate') {
      //   this.setData({
      //     beginDate: "",
      //     beginDateFormat: ""
      //   })
      //   this.modifyData()
      // }
      // if (prop == 'endDate') {
      //   this.setData({
      //     endDate: "",
      //     endDateFormat: ""
      //   })
      //   this.modifyData()
      // }
    },
    // 添加图片
    addImg() {
      wx.chooseMedia({
        mediaType: "image",
        sourceType: ["album", "camera"],
        success: res => {
          let list = res.tempFiles.map(item => item.tempFilePath)
          this.setData({
            imgList: this.data.imgList.concat(list)
          })
          this.modifyData()
        },
        fail: err => {

        }
      })
    },
    // 删除图片
    deleteImg(e) {
      let index = e.currentTarget.dataset.index
      this.data.imgList.splice(index, 1)
      this.setData({
        imgList: this.data.imgList
      })
      this.modifyData()
    },
    // 预览图片
    previewImg(e) {
      wx.previewImage({
        urls: this.data.imgList,
        current: e.currentTarget.dataset.item
      })
    },
    // 选择视频
    addVideo() {
      wx.chooseMedia({
        count: 1,
        mediaType: ['video'],
        sourceType: ['album', 'camera'],
        maxDuration: 30,
        camera: 'back',
        success: res => {
          let tempFilePath = res.tempFiles[0].tempFilePath
          this.setData({
            video: tempFilePath
          })
          this.modifyData()
          // wx.getFileSystemManager().readFile({
          //   filePath: tempFilePath,
          //   encoding: "base64",
          //   success: (res) => {
          //     // 这里再次给赋值，因为没有调用setData所以不会影响页面变化
          //     this.data.video = res.data
          //     this.modifyData()
          //   }
          // })
        }
      })
    },
    // 删除视频
    deleteVideo() {
      this.setData({
        video: ''
      })
      this.modifyData()
    },
    // 单选
    radioChange(e) {
      this.setData({
        radio: e.detail
      })
      this.modifyData()
    },
    // 定位获取数据
    async getLocation() {
      setTimeout(async ()=>{
      wx.showLoading({
        title: '定位中',
        mask:true,
      })
      try{
        const res = await initLocationPersmiss()
        this.setData({
          latitude: res.location.lat,
          longitude: res.location.lng,
          address:res.formatted_addresses.recommend
        })
        this.modifyData()
      }finally{
        wx.hideLoading()
      }
    },300)
    },
    // 选择定位
    chooseLocation(){
      const {latitude,longitude} = this.data
      const params = latitude?{latitude,longitude}:{}
      wx.chooseLocation(Object.assign(params,{
        success:res=>{
          this.setData({
            latitude:res.latitude,
            longitude:res.longitude,
            address:res.address+res.name
          })
          this.modifyData()
        },
      }))
    },
    saveRecord(e){
      console.log(111)
      if(e.detail){
          this.setData({
              recordSound:e.detail.file
          })
      }
      this.modifyData()
    },
    recordSound(){
      this.selectComponent("#sound-record-two").start()
    },
    endSound(){
        this.selectComponent("#sound-record-two").end()
    },
    // 删除录音
    delRecordSound(){
      this.setData({
        recordSound:"",
      })
    },
    // 修改数据
    modifyData() {
      // let fieldType = this.data.formItem.fieldType
      // let multiFlag = this.data.formItem.multiFlag
      const {fieldType,multiFlag} = this.data.formItem
      let {inputValue,selectedIds,beginDateFormat,endDateFormat,imgList,video,radio,address,latitude,longitude,recordSound} = this.data
      let value = ""
      let httpsReg = /^https/
      switch (fieldType) {
        case 1:
          value = inputValue
          break
        case 2:
          value = selectedIds
          break
        case 3:
          if (multiFlag) {
            if (endDateFormat) {
              value = beginDateFormat + ',' + endDateFormat
            } else {
              value = beginDateFormat
            }  
          } else {
            value = beginDateFormat
          }
          break
        case 4:
          imgList = [...imgList]
        
          // 需要把临时路径转化base64
          imgList.forEach((item, index) => {
            if (!httpsReg.test(item)) {
              let res = wx.getFileSystemManager().readFileSync(item, "base64")
              imgList[index] = res
            }
          })
          value = imgList.join(",")
          break
        case 5:
          if (!httpsReg.test(video)) {
            value = wx.getFileSystemManager().readFileSync(video, "base64")
            // imgList[index] = res
          }
          // wx.getFileSystemManager().readFile({
          //   filePath: tempFilePath,
          //   encoding: "base64",
          //   success: (res) => {
          //     // 这里再次给赋值，因为没有调用setData所以不会影响页面变化
          //     this.data.video = res.data
          //     this.modifyData()
          //   }
          // })
          // value = video
          break
        case 6:
          value = radio
          break
        case 7:
          value = address?JSON.stringify({
            address,
            latitude,
            longitude
          }):""
          break
        case 8:
          console.log(recordSound,"录音的结果")
          value = recordSound
          break
      }
      this.triggerEvent("modifydata", { value, index: this.data.currentIndex })
    },
  }
})
